#include "ToolManager.h"
#include "ToolBase.h"
#include "ToolFactory.h"

ToolManager *ToolManager::self = NULL;

ToolManager::~ToolManager()
{
    self = nullptr;
}

ToolManager::ToolManager(ToolManager *myself)
{
    assert(self == nullptr);
    self = myself;
}

ToolBase *
ToolManager::activeTool()
{
    return m_tools.empty() ? nullptr : m_tools.front();
}

void
ToolManager::addTool(ToolBase *tool)
{
    m_tools.remove(tool);
    m_tools.push_front(tool);
    tool->reset();
}

void
ToolManager::removeTool(ToolBase *tool)
{
    if(! m_tools.empty() && m_tools.front() == tool)
    {
        tool->reset();
    }
}

void
ToolManager::selectTool(ToolBase *tool)
{
    if(! m_tools.empty())
    {
        m_tools.front()->reset();
    }
    m_tools.remove(tool);
    m_tools.push_front(tool);
    //toolChanged(m_tools.front());
}

void
ToolManager::unselectTool(ToolBase *tool)
{
    if(m_tools.empty()) return;
    tool->reset();
    m_tools.remove(tool);
    m_tools.push_back(tool);
    //toolChanged(m_tools.front());
}

void
ToolManager::loadTools(ToolFactory *factory)
{
    if(factory != nullptr)
    {
        vector<int> tools = factory->availableTools();
        foreach(int id, tools)
        {
            ToolBase * tool = factory->createTool(id);
            if(tool != nullptr)
                addTool(tool);
        }
    }
}
